import React from 'react';
import { Route, Redirect } from 'react-router-dom';
// import RenderAuthorized from '@/components/Authorized';
import Exception from '@/components/Exception';
import Authorized from '../utils/Authorized';
import { matchRoutes } from 'react-router-config';
import intersection from 'lodash/intersection';
import { formatMessage } from 'umi/locale';
import Link from 'umi/link';
import { getAccessToken } from '../utils/request';

// const Authorized = RenderAuthorized(getAuthority());
 const { AuthorizedRoute } = Authorized;




export default ({ children, route, location }) => {
  const routes = matchRoutes(route.routes, location.pathname);
  let authorities = ['admin'];
  routes.forEach(item => {
    if (Array.isArray(item.route.authority) && item.route.authority.length) {
      // authorities.push(...item.route.authority);
      // authorities = [...authorities,...item.route.authority];
      authorities = [...item.route.authority];
    } else if (typeof item.route.authority === 'string' && item.route.authority) {
      authorities.push(item.route.authority);
    }
  });
  //
  // console.log('authorities',authorities)
  // console.log('routes',routes)
  // console.log('intersection',intersection(authorities));
  // console.log('children',authorities.length );

  const noMatch = (
    <Exception
      type="403"
      desc={formatMessage({ id: 'app.exception.description.403' })}
      linkElement={Link}
      backText={formatMessage({ id: 'app.exception.back' })}
    />
  );
  return (
    <AuthorizedRoute
      {...children.props}
      authority={authorities.length === 0 ? undefined : intersection(authorities)}
      redirectPath={getAccessToken() ? "/403" : "/user/login"}
    />
  );

  // return (
  //   <Authorized
  //     authority={authorities.length === 0 ? undefined : intersection(...authorities)}
  //     noMatch={noMatch}
  //   >
  //     {children}
  //   </Authorized>
  // );
};
